昨天將解碼的架構寫好了之後,今天來寫解碼器。
這裡先將要調資料的網址處理一下之後,嘗試能否調到資料,如果不行就會及時報錯,調到資料後再將資料丟給呼叫這個函式的地方。
import Foundation
class NetworkManager: NSObject {
static let shared = NetworkManager()
func getWeatherData<D: Decodable>(city: String, completion: @escaping (D?) -> Void, failure: @escaping (String?) -> Void) {
let address = "https://api.openweathermap.org/data/2.5/weather?"
if let url = URL(string: address + "q=\(city)" + "&units=metric&lang=zh_tw&appid=" + NetworkConstants.apiKey) {
URLSession.shared.dataTask(with: url) {(data, response, error) in
if let error = error {
failure("Error: \(error.localizedDescription)")
} else if let response = response as? HTTPURLResponse, let data = data {
print("Status code: \(response.statusCode)")
#if DEBUG
let content = String(data: data, encoding: .utf8) ?? ""
print(content)
#endif
let decoder = JSONDecoder()
if let weatherData = try? decoder.decode(D.self, from: data) {
completion(weatherData)
} else {
failure("error")
}
}
}.resume()
} else {
failure("Invalid URL.")
}
}
}
那麼今天就到這裡,明天繼續將資料和畫面做連動。